import { useState, useCallback } from 'react';
import { CollapsibleItem, SearchResult } from '../types';

export const useSearch = (items: CollapsibleItem[]) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
  const [highlightedItemId, setHighlightedItemId] = useState<string | null>(null);
  const [currentResultIndex, setCurrentResultIndex] = useState(0);

  // 搜索函数
  const searchInItems = useCallback((
    items: CollapsibleItem[], 
    query: string
  ): SearchResult[] => {
    if (!query.trim()) return [];

    const regex = new RegExp(query, 'gi');
    const results: SearchResult[] = [];
    
    items.forEach(item => {
      // 搜索标题
      const titleMatch = item.title.match(regex);
      if (titleMatch) {
        results.push({
          itemId: item.id,
          title: item.title,
          content: item.content,
          matchType: 'title',
          matchIndex: item.title.toLowerCase().indexOf(query.toLowerCase()),
          matchLength: query.length
        });
      }

      // 搜索内容
      const contentMatch = item.content.match(regex);
      if (contentMatch) {
        results.push({
          itemId: item.id,
          title: item.title,
          content: item.content,
          matchType: 'content',
          matchIndex: item.content.toLowerCase().indexOf(query.toLowerCase()),
          matchLength: query.length
        });
      }
    });

    return results;
  }, []);

  // 执行搜索
  const performSearch = useCallback((query: string) => {
    setSearchQuery(query);
    
    if (!query.trim()) {
      setSearchResults([]);
      setHighlightedItemId(null);
      setCurrentResultIndex(0);
      return;
    }

    const results = searchInItems(items, query);
    setSearchResults(results);
    setCurrentResultIndex(0);
    
    // 如果有结果，高亮第一个匹配项
    if (results.length > 0) {
      setHighlightedItemId(results[0].itemId);
    } else {
      setHighlightedItemId(null);
    }
  }, [items, searchInItems]);

  // 清除搜索
  const clearSearch = useCallback(() => {
    setSearchQuery('');
    setSearchResults([]);
    setHighlightedItemId(null);
    setCurrentResultIndex(0);
  }, []);

  // 导航到上一个结果
  const navigateToPrevious = useCallback(() => {
    if (currentResultIndex > 0) {
      const newIndex = currentResultIndex - 1;
      setCurrentResultIndex(newIndex);
      setHighlightedItemId(searchResults[newIndex].itemId);
    }
  }, [currentResultIndex, searchResults]);

  // 导航到下一个结果
  const navigateToNext = useCallback(() => {
    if (currentResultIndex < searchResults.length - 1) {
      const newIndex = currentResultIndex + 1;
      setCurrentResultIndex(newIndex);
      setHighlightedItemId(searchResults[newIndex].itemId);
    }
  }, [currentResultIndex, searchResults]);

  // 检查项目是否应该被高亮
  const isItemHighlighted = useCallback((itemId: string) => {
    return highlightedItemId === itemId;
  }, [highlightedItemId]);

  return {
    searchQuery,
    searchResults,
    highlightedItemId,
    currentResultIndex,
    performSearch,
    clearSearch,
    navigateToPrevious,
    navigateToNext,
    isItemHighlighted
  };
};
